// 这是一个全局的图片or视频浏览弹窗 
import React, { useState, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import logo from "@/assets/images/logo.webp"// 图片背面的logo
interface ImageViewerProps {
  /** 是否显示组件 */
  show: boolean;
  /** 媒体URL（图片或视频） */
  mediaUrl: string;
  /** 媒体类型 */
  mediaType?: 'image' | 'video';
  /** 媒体alt文本 */
  mediaAlt?: string;
  /** 关闭回调函数 */
  onClose: () => void;
}

// 向后兼容的类型别名
interface LegacyImageViewerProps {
  show: boolean;
  imageUrl: string;
  imageAlt?: string;
  onClose: () => void;
}

/**
 * 媒体浏览组件
 * 全屏弹窗展示图片或视频，支持毛玻璃蒙版、居中展示、点击关闭等功能
 */
const ImageViewer: React.FC<ImageViewerProps | LegacyImageViewerProps> = (props) => {
  const { t } = useTranslation();
  const {
    show,
    onClose
  } = props;

  // 向后兼容处理
  const mediaUrl = 'mediaUrl' in props ? props.mediaUrl : (props as LegacyImageViewerProps).imageUrl;
  const mediaType = 'mediaType' in props ? props.mediaType || 'image' : 'image';
  const mediaAlt = 'mediaAlt' in props ? props.mediaAlt || '媒体预览' : (props as LegacyImageViewerProps).imageAlt || '图片预览';

  // 图片交互相关状态
  const [isDragging, setIsDragging] = useState(false);
  const [startX, setStartX] = useState(0);
  const [startY, setStartY] = useState(0);
  const [rotateX, setRotateX] = useState(0);
  const [rotateY, setRotateY] = useState(0);
  const [isFlipped, setIsFlipped] = useState(false);
  const imageRef = useRef<HTMLDivElement>(null);
  const cardRef = useRef<HTMLDivElement>(null);
  const pressTimerRef = useRef<NodeJS.Timeout | null>(null);
  const touchMoveEnabled = useRef(false);

  // 图片尺寸状态
  const [imageDimensions, setImageDimensions] = useState({ width: 0, height: 0 });

  // 检查URL有效性
  const hasValidUrl = Boolean(mediaUrl && mediaUrl.trim() !== '');

  // 处理蒙版点击关闭
  const handleBackdropClick = (e: React.MouseEvent) => {
    // 只有点击蒙版本身时才关闭，点击图片不关闭
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  // 处理ESC键关闭
  React.useEffect(() => {
    if (!show) return;

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [show, onClose]);

  // 直接控制滚动
  React.useEffect(() => {
    if (show) {
      const originalOverflow = document.body.style.overflow;
      document.body.style.overflow = 'hidden';

      return () => {
        document.body.style.overflow = originalOverflow;
      };
    }
  }, [show]);

  // 组件卸载时确保恢复滚动
  React.useEffect(() => {
    return () => {
      document.body.style.overflow = '';
    };
  }, []);

  // 鼠标按下事件处理（PC端）
  const handleMouseDown = (e: React.MouseEvent) => {
    if (mediaType !== 'image') return;

    // 清除任何现有的计时器
    if (pressTimerRef.current) {
      clearTimeout(pressTimerRef.current);
    }

    // 设置长按计时器
    pressTimerRef.current = setTimeout(() => {
      setIsDragging(true);
      setStartX(e.clientX);
      setStartY(e.clientY);
    }, 500); // 长按500毫秒后开始旋转
  };

  // 鼠标移动事件处理（PC端）
  const handleMouseMove = (e: MouseEvent) => {
    if (!isDragging || mediaType !== 'image') return;

    const deltaX = e.clientX - startX;
    const deltaY = e.clientY - startY;

    // 计算旋转角度
    const newRotateY = deltaX * 0.5;
    const newRotateX = -deltaY * 0.5;

    setRotateX(newRotateX);
    setRotateY(newRotateY);
  };

  // 鼠标释放事件处理（PC端）
  const handleMouseUp = () => {
    // 清除长按计时器
    if (pressTimerRef.current) {
      clearTimeout(pressTimerRef.current);
      pressTimerRef.current = null;
    }

    if (isDragging) {
      setIsDragging(false);

      // 如果旋转超过一定角度，自动翻转卡片
      if (Math.abs(rotateY) > 60) {
        setIsFlipped(!isFlipped);
      }

      // 重置旋转角度
      setRotateX(0);
      setRotateY(0);
    }
  };

  // 触摸开始事件处理（移动端）
  const handleTouchStart = (e: React.TouchEvent) => {
    if (mediaType !== 'image') return;

    // 清除任何现有的计时器
    if (pressTimerRef.current) {
      clearTimeout(pressTimerRef.current);
    }

    // 立即记录起始位置，不管是否长按
    setStartX(e.touches[0].clientX);
    setStartY(e.touches[0].clientY);

    // 设置长按计时器
    pressTimerRef.current = setTimeout(() => {
      setIsDragging(true);
      touchMoveEnabled.current = true; // 启用触摸移动
      // 注意：这里不再调用preventDefault，因为在异步回调中调用已经太晚了
    }, 500); // 长按500毫秒后开始旋转
  };

  // 触摸移动事件处理（移动端）
  const handleTouchMove = (e: React.TouchEvent) => {
    if (!isDragging || mediaType !== 'image') return;

    const deltaX = e.touches[0].clientX - startX;
    const deltaY = e.touches[0].clientY - startY;

    // 计算旋转角度
    const newRotateY = deltaX * 0.5;
    const newRotateX = -deltaY * 0.5;

    setRotateX(newRotateX);
    setRotateY(newRotateY);

    // 阻止页面滚动，但仅在长按触发后
    if (touchMoveEnabled.current) {
      e.preventDefault();
    }
  };

  // 触摸结束事件处理（移动端）
  const handleTouchEnd = (e: React.TouchEvent) => {
    // 清除长按计时器
    if (pressTimerRef.current) {
      clearTimeout(pressTimerRef.current);
      pressTimerRef.current = null;
    }

    // 如果没有移动很多，并且没有拖动，则视为点击
    const endX = e.changedTouches[0].clientX;
    const endY = e.changedTouches[0].clientY;
    const deltaX = endX - startX;
    const deltaY = endY - startY;
    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

    if (distance < 10 && !isDragging) {
      // 视为点击操作，触发翻转
      setIsFlipped(!isFlipped);
    } else if (isDragging) {
      setIsDragging(false);
      touchMoveEnabled.current = false;

      // 如果旋转超过一定角度，自动翻转卡片
      if (Math.abs(rotateY) > 60) {
        setIsFlipped(!isFlipped);
      }

      // 重置旋转角度
      setRotateX(0);
      setRotateY(0);
    }
  };

  // 点击事件处理
  const handleClick = (e: React.MouseEvent) => {
    if (mediaType !== 'image' || isDragging) return;

    // 直接翻转卡片
    setIsFlipped(!isFlipped);
  };

  // 添加和移除全局事件监听器
  useEffect(() => {
    if (isDragging) {
      window.addEventListener('mousemove', handleMouseMove);
      window.addEventListener('mouseup', handleMouseUp);
    }

    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isDragging]);

  // 当组件显示或隐藏时重置状态
  useEffect(() => {
    if (!show) {
      setRotateX(0);
      setRotateY(0);
      setIsDragging(false);
      setIsFlipped(false);
      touchMoveEnabled.current = false;
      if (pressTimerRef.current) {
        clearTimeout(pressTimerRef.current);
        pressTimerRef.current = null;
      }
    }
  }, [show]);

  // 获取正确的变换样式
  const getTransformStyle = () => {
    if (isFlipped) {
      return `rotateY(180deg) rotateX(${rotateX}deg) rotateY(${-rotateY}deg)`;
    } else {
      return `rotateY(0deg) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
    }
  };

  // 处理图片加载并设置尺寸
  const handleImageLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
    const img = e.currentTarget;

    // 计算图片尺寸，确保在视口范围内
    const viewportWidth = window.innerWidth * 0.9; // 90% 视口宽度
    const viewportHeight = window.innerHeight * 0.85; // 85% 视口高度

    let width = img.naturalWidth;
    let height = img.naturalHeight;

    // 调整尺寸以适应视口
    const ratio = Math.min(
      viewportWidth / width,
      viewportHeight / height
    );

    // 如果图片比视口大，按比例缩小
    if (ratio < 1) {
      width = width * ratio;
      height = height * ratio;
    }

    // 确保尺寸至少达到最小值
    width = Math.max(width, 300);
    height = Math.max(height, 300);

    // 设置图片尺寸状态
    setImageDimensions({ width, height });

    // console.log('图片加载成功:', mediaUrl);
  };

  // 简单模式下直接显示图片
  const renderSimpleImage = () => (
    <div className="relative w-full h-full flex items-center justify-center">
      <img
        src={mediaUrl}
        alt={mediaAlt}
        loading="eager"
        className="object-contain rounded-lg shadow-2xl"
        style={{
          maxWidth: '95vw',
          maxHeight: '95vh',
          borderRadius: '12px',
          boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.3)',
        }}
        onError={(e) => {
          // console.error('图片加载失败:', mediaUrl);
          console.error('image load failed',mediaUrl);
          const target = e.target as HTMLImageElement;
          const parent = target.parentElement;
          if (parent) {
            parent.innerHTML = `
              <div style="
                width: 95vw; 
                height: 95vh; 
                max-width: 800px; 
                max-height: 1000px; 
                background: rgba(0,0,0,0.1); 
                border-radius: 12px; 
                display: flex; 
                flex-direction: column; 
                align-items: center; 
                justify-content: center; 
                color: #666;
                padding: 20px;
                text-align: center;
              ">
                <i class="fas fa-exclamation-triangle" style="font-size: 2rem; margin-bottom: 1rem; color: #f59e0b;"></i>
                <div style="font-size: 1rem; margin-bottom: 0.5rem;">图片加载失败</div>
                <div style="font-size: 0.8rem; color: #999; word-break: break-all;">${mediaUrl}</div>
              </div>
            `;
          }
        }}
        onLoad={() => {
          // console.log('图片加载成功:', mediaUrl);
        }}
      />
    </div>
  );

  return (
    <div
      className={`fixed inset-0 flex items-center justify-center transition-all duration-300`}
      style={{
        zIndex: 9999, // 确保覆盖所有内容，包括侧边栏
        display: show ? 'flex' : 'none',
        backdropFilter: show ? 'blur(16px)' : 'blur(0px)',
        WebkitBackdropFilter: show ? 'blur(16px)' : 'blur(0px)',
        backgroundColor: show ? 'rgba(0, 0, 0, 0.3)' : 'rgba(255, 255, 255, 0)', // 改为深色背景，让图片更突出
        transform: show ? 'scale(1)' : 'scale(0.95)',
        opacity: show ? 1 : 0,
        pointerEvents: show ? 'auto' : 'none',
        padding: '10px' // 添加内边距，避免图片贴边
      }}
      onClick={handleBackdropClick}
    >
      {/* 媒体容器 */}
      <div
        className={`relative flex items-center justify-center transition-transform duration-300 ${show ? 'scale-100' : 'scale-75'}`}
        style={{ width: '100%', height: '100%' }}
      >
        {!hasValidUrl ? (
          /* 无效URL提示 */
          <div className="flex flex-col items-center justify-center p-8 text-center text-gray-400">
            <i className="fas fa-exclamation-triangle text-3xl mb-4 text-yellow-500"></i>
            <div className="text-lg mb-2">{t('ImageViewer.invalidUrlTitle')}</div>
            <div className="text-sm">{t('ImageViewer.invalidUrlDesc')}</div>
          </div>
        ) : mediaType === 'video' ? (
          /* 视频展示 */
          <div className="relative w-full h-full flex items-center justify-center">
            <video
              src={mediaUrl}
              controls
              preload="metadata" // 预加载元数据，加快显示速度
              className="object-contain rounded-lg shadow-2xl"
              style={{
                maxWidth: '90vw',
                maxHeight: '90vh',
                borderRadius: '12px',
                boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.3)',
              }}
              onError={(e) => {
                console.error(t('ImageViewer.videoLoadFailedTitle'), mediaUrl);
                const target = e.target as HTMLVideoElement;
                const parent = target.parentElement;
                if (parent) {
                  parent.innerHTML = `
                    <div style="
                      width: 90vw; 
                      height: 90vh; 
                      max-width: 800px; 
                      max-height: 900px; 
                      background: rgba(0,0,0,0.1); 
                      border-radius: 12px; 
                      display: flex; 
                      flex-direction: column; 
                      align-items: center; 
                      justify-content: center; 
                      color: #666;
                      padding: 20px;
                      text-align: center;
                    ">
                      <i class="fas fa-video-slash" style="font-size: 2rem; margin-bottom: 1rem; color: #f59e0b;"></i>
                      <div style="font-size: 1rem; margin-bottom: 0.5rem;">${t('ImageViewer.videoLoadFailedTitle')}</div>
                      <div style="font-size: 0.8rem; color: #999; word-break: break-all;">${mediaUrl}</div>
                    </div>
                  `;
                }
              }}
              onLoadedData={() => {
                // console.log(t('ImageViewer.mediaPreview'), mediaUrl);
              }}
            />
          </div>
        ) : (
          /* 图片展示 - 使用3D翻转卡片方式 */
          <div
            ref={imageRef}
            className="relative flex items-center justify-center"
            style={{
              perspective: '1000px',
              cursor: isDragging ? 'move' : 'pointer',
              touchAction: isDragging ? 'none' : 'auto', // 在拖动时禁用浏览器的默认触摸行为
            }}
            onMouseDown={handleMouseDown}
            onTouchStart={handleTouchStart}
            onTouchMove={handleTouchMove}
            onTouchEnd={handleTouchEnd}
            onClick={handleClick}
          >
            {/* 隐藏的图片用于获取尺寸 */}
            {show && (
              <img
                src={mediaUrl}
                alt=""
                style={{ display: 'none' }}
                onLoad={handleImageLoad}
              />
            )}
            <div
              ref={cardRef}
              className="relative transition-transform"
              style={{
                width: imageDimensions.width || 'auto',
                height: imageDimensions.height || 'auto',
                maxWidth: '95vw',
                maxHeight: '95vh',
                transformStyle: 'preserve-3d',
                borderRadius: '12px',
                transform: getTransformStyle(),
                transition: isDragging ? 'none' : 'transform 0.5s',
              }}
            >
              {/* 图片正面 */}
              <div
                className="absolute flex items-center justify-center"
                style={{
                  width: '100%',
                  height: '100%',
                  backfaceVisibility: 'hidden',
                  transform: 'rotateY(0deg)',
                  borderRadius: '12px',
                  boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.3)',
                  overflow: 'hidden',
                }}
              >
                <img
                  src={mediaUrl}
                  alt={mediaAlt}
                  loading="eager"
                  style={{
                    width: '100%',
                    height: '100%',
                    objectFit: 'contain',
                    borderRadius: '12px',
                  }}
                  onError={(e) => {
                    console.error(t('ImageViewer.imageLoadFailedTitle'), mediaUrl);
                    const target = e.target as HTMLImageElement;
                    const parent = target.parentElement;
                    if (parent) {
                      parent.innerHTML = `
                    <div style="
                      width: 100%; 
                      height: 100%; 
                      background: rgba(0,0,0,0.1); 
                      border-radius: 12px; 
                      display: flex; 
                      flex-direction: column; 
                      align-items: center; 
                      justify-content: center; 
                      color: #666;
                      padding: 20px;
                      text-align: center;
                    ">
                      <i class="fas fa-exclamation-triangle" style="font-size: 2rem; margin-bottom: 1rem; color: #f59e0b;"></i>
                      <div style="font-size: 1rem; margin-bottom: 0.5rem;">${t('ImageViewer.imageLoadFailedTitle')}</div>
                      <div style="font-size: 0.8rem; color: #999; word-break: break-all;">${mediaUrl}</div>
                    </div>
                  `;
                    }
                  }}
                />
              </div>
              {/* 图片背面 */}
              <div
                className="absolute flex items-center justify-center bg-gray-800"
                style={{
                  width: '100%',
                  height: '100%',
                  backfaceVisibility: 'hidden',
                  transform: 'rotateY(180deg)',
                  borderRadius: '12px',
                  boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.3)',
                  color: 'white',
                }}
              >
                <div style={{borderRadius:"0.8rem"}} className="flex items-center justify-center bg-[rgb(0,0,0)] w-full h-full">
                  <img 
                    src={logo} 
                    alt="Logo" 
                    className="w-[20rem] h-[9rem] object-contain"
                  />
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 关闭按钮 */}
        <button
          onClick={onClose}
          className="absolute top-3 right-3 sm:top-4 sm:right-4 w-8 h-8 sm:w-10 sm:h-10 bg-gray-800 bg-opacity-80 hover:bg-opacity-90 rounded-full flex items-center justify-center transition-all duration-200 group"
          style={{
            backdropFilter: 'blur(8px)',
            WebkitBackdropFilter: 'blur(8px)',
          }}
          aria-label={t('ImageViewer.close')}
        >
          <i
            className="fas fa-times text-white text-lg sm:text-xl group-hover:scale-110 transition-transform duration-200"
          />
        </button>

        {/* 交互提示 - 仅在图片模式下显示 */}
        {mediaType === 'image' && hasValidUrl && (
          <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 text-white text-xs sm:text-sm bg-black bg-opacity-50 px-3 py-1 rounded-full backdrop-blur-sm">
            <i className={`fas ${isFlipped ? 'fa-sync-alt' : 'fa-hand-pointer'} mr-1`}></i>
            <span>{isFlipped ? t('ImageViewer.flipHintBack') : t('ImageViewer.flipHintFront')}</span>
          </div>
        )}
      </div>
    </div>
  );
};

export default ImageViewer; 